package cn.lzy.web.client;

import cn.lzy.dao.UserAuthorityMapper;
import cn.lzy.dao.UserMapper;
import cn.lzy.dao.zhuxiaob;
import cn.lzy.model.domain.User;
import cn.lzy.model.domain.UserAuthority;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author: gao dan
 * @CreateTime: 2023-11-02  23:45
 */
@Controller
public class UserController {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAuthorityMapper userAuthorityMapper;
    @Autowired
    private cn.lzy.dao.zhuxiaob zhuxiaob;


    // 向用户信息删除页跳转
    @GetMapping("/deleteUser")
    public String deleteUser() {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        // 查询当前用户名id
        int userId = userMapper.getUserByUsername(username);
        userMapper.deleteUser(userId);
        userAuthorityMapper.deleteUserAuthority(userId);
        // 清除认证信息
        Authentication authentication1 = SecurityContextHolder.getContext().getAuthentication();
        if (authentication1 != null) {
            SecurityContextHolder.getContext().setAuthentication(null);
        }
        return "user/delete_finish";
    }


    // 新用户注册
    @GetMapping("/toRegister") // http://localhost:8090/toRegister
    public String showRegisterForm(Model model) {
        model.addAttribute("user", new User());

        return "user/registerUser";
    }

    // 用户注册提交处理
    @PostMapping(value = "/registerUser")
    public String registerUser(@RequestParam("username") String username,
                               @RequestParam("password") String password,
                               @RequestParam("email") String email) {

        // 创建新用户
        User user = new User();
        user.setUsername(username);
        // 对密码进行加密
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodedPassword = encoder.encode(password);
        user.setPassword(encodedPassword);
        user.setEmail(email);

        // 判断用户是否注册
        if (isUsernameExist(username)) {
            return "user/user_error";
        } else {
            userMapper.insertUser(user);
            // 获取新插入的用户ID
            Integer userId = userMapper.getNewUserId();
            // 插入用户权限关联信息到t_user_authority表
            UserAuthority userAuthority = new UserAuthority();
            userAuthority.setUserId(userId);
            userAuthority.setAuthorityId(2); // 假设默认权限ID为2
            userAuthorityMapper.insertUser(userAuthority);

            return "user/user_finish";
        }
    }



    // 判断username是否存在
    public boolean isUsernameExist(String username) {
        List<User> users = userMapper.findByUsername(username);
        return !users.isEmpty();
    }

    // 向用户信息页跳转
    @GetMapping("/userInformation")
    public String userInformation(Model model) {
        // 获取当前登录用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        // 获取当前用户的邮箱
        String email = userMapper.getEmailByUsername(username);
        // 获取用户账号创建时间
        String created = userMapper.getCreatedByUsername(username);
        model.addAttribute("username", username);
        model.addAttribute("email", email);
        model.addAttribute("created", created);
        return "user/account_info";
    }

    // 向用户修改页跳转
    // http://localhost:8090/toUpdate
    @GetMapping("/toUpdate")
    public String toUpdate() {
        return "user/updateUser";
    }


    @PostMapping(value = "/updateUser")
    public String updateUser(@RequestParam String username, HttpServletRequest request) {
            String usernames = SecurityContextHolder.getContext().getAuthentication().getName();
            if (isUsernameExist(username)){
                return "user/user_error1";
            }else {
                User user = new User();
                user.setUsername(username);
            }
            System.out.println(username);

            String csrf_token = request.getParameter("_csrf");
            System.out.println(csrf_token);
// 获取应用上下文
            SecurityContext context = SecurityContextHolder.getContext();
// 获取登录的用户信息
            Authentication authentication = context.getAuthentication();
            UserDetails principal = (UserDetails) authentication.getPrincipal();
// 获取登录的用户id
            Integer updateId = zhuxiaob.findByCustomer(principal.getUsername());
// 更新用户表中对应id的用户名

        // 清除认证信息
        Authentication authentication1 = SecurityContextHolder.getContext().getAuthentication();
        if (authentication1 != null) {
            SecurityContextHolder.getContext().setAuthentication(null);
        }

            Integer result = zhuxiaob.updareCustomer(username, updateId);
            return "user/user_finish1";
        }
        }





